#include "ShotCutWriter.h"

ShotCutWriter::ShotCutWriter(ShotCutTimeLine* VideoTimeLine)
: WriteTimeLine(VideoTimeLine){}

ShotCutWriter::~ShotCutWriter()
{
    delete VideoWriter;
    delete WriteTimeLine;
}

void ShotCutWriter::RenderToFile(std::string FileName)
{
    if(VideoWriter == nullptr && !FileName.empty())
    {
        VideoWriter = new FFmpegWriter(FileName);
    }

    const std::shared_ptr<GlobalData> Global = GlobalData::GetGlobalData();
    VideoWriter->SetVideoOptions("libx264", Global->GetVideoWidth(), Global->GetVideoHeight(), Fraction(Global->GetFps(), 1), Global->GetVideoBitRate());
    VideoWriter->SetAudioOptions("libmp3lame", Global->GetAudioSampleRate(), Global->GetAudioBitRate());
    
    if(WriteTimeLine != nullptr)
    {
        std::shared_ptr<Timeline> VideoTimeLine = WriteTimeLine->VideoTimeLine;
        if(VideoTimeLine != nullptr)
        {
            if(!VideoWriter->IsOpen())
            {
                VideoWriter->Open();
            }
            if(!VideoTimeLine->IsOpen())
            {
                VideoTimeLine->Open();
            }
        
            int64_t MaxFrame = VideoTimeLine->GetMaxFrame();
            for (int64_t frame = 1; frame <= MaxFrame; frame++)
            {
                VideoWriter->WriteFrame(VideoTimeLine->GetFrame(frame));
                double p = (double)frame / (double)MaxFrame;
                cout << "cycsprogress:" << setprecision(3) << p << ";" << endl;
            }

            if(VideoWriter->IsOpen())
            {
                VideoWriter->Close();
            }
            if(VideoTimeLine->IsOpen())
            {
                VideoTimeLine->Close();
            }
        }
    }
}


